<template>
  <div class="sheep-sale-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="mb-4">
      <el-breadcrumb-item :to="{ path: '/OnePages' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>羊场业务</el-breadcrumb-item>
      <el-breadcrumb-item>羊只销售</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="title">羊只销售-新增</h1>
      <div class="subtitle">管理羊只销售记录，支持新增、编辑和删除操作</div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="addNewRecord" :icon="Plus" class="mr-2">
        新增
      </el-button>
      <el-button type="primary" @click="saveRecords" :icon="Check" class="mr-2">
        保存
      </el-button>
      <el-button @click="resetForm" :icon="Refresh" class="mr-2">
        撤销
      </el-button>
      <el-button type="danger" @click="deleteSelected" :icon="Delete">
        删除
      </el-button>
    </div>

    <!-- 销售基本信息卡片 -->
    <el-card class="mb-4" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">销售基本信息</span>
        </div>
      </template>
      <el-form :model="saleInfo" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="销售日期" required>
              <el-date-picker v-model="saleInfo.salesDate" type="date" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户" required>
              <el-input v-model="saleInfo.customer" placeholder="请输入客户" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售员">
              <el-input v-model="saleInfo.salesperson" placeholder="请输入销售员" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="部门">
              <el-input v-model="saleInfo.department" placeholder="请输入部门" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库">
              <el-input v-model="saleInfo.warehouse" placeholder="请输入仓库" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货地址">
              <el-input v-model="saleInfo.shippingaddress" placeholder="请输入收货地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单据号">
              <el-input v-model="saleInfo.documentnumber" placeholder="请输入单据号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="流水号">
              <el-input v-model="saleInfo.serialnumber" placeholder="请输入流水号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 编辑表格卡片 -->
    <el-card class="mb-4" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">销售羊只信息</span>
          <div class="table-actions">
            <el-button type="success" plain @click="addRow" :icon="Plus" size="small" class="mr-2">
              增行
            </el-button>
            <el-button type="danger" plain @click="deleteRow" :icon="Delete" size="small">
              删行
            </el-button>
          </div>
        </div>
      </template>

      <!-- 编辑表格 -->
      <el-table :data="editingData" border style="width: 100%" v-loading="isLoading" empty-text="暂无数据，请点击'增行'添加">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="earNumber" label="*耳号" width="120">
          <template #default="{ row }">
            <el-input v-model="row.earNumber" placeholder="请输入耳号" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="clinch" label="成交价(元)" width="120">
          <template #default="{ row }">
            <el-input v-model="row.clinch" placeholder="请输入成交价" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="pricing" label="定价(元)" width="120">
          <template #default="{ row }">
            <el-input v-model="row.pricing" placeholder="请输入定价" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="折扣比例" width="120">
          <template #default="{ row }">
            <el-input v-model="row.discount" placeholder="请输入折扣比例" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="level" label="等级" width="80">
          <template #default="{ row }">
            <el-input v-model="row.level" placeholder="请输入等级" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="variety" label="品种" width="120">
          <template #default="{ row }">
            <el-input v-model="row.variety" placeholder="请输入品种" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="{ row }">
            <el-select v-model="row.sex" placeholder="请选择" clearable>
              <el-option label="公" value="公" />
              <el-option label="母" value="母" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="羊只类型" width="120">
          <template #default="{ row }">
            <el-input v-model="row.type" placeholder="请输入羊只类型" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="reproduction" label="繁殖状态" width="120">
          <template #default="{ row }">
            <el-input v-model="row.reproduction" placeholder="请输入繁殖状态" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="building" label="栋舍" width="120">
          <template #default="{ row }">
            <el-select v-model="row.building" placeholder="请选择" clearable>
              <el-option label="大羊舍" value="大羊舍" />
              <el-option label="配种舍" value="配种舍" />
              <el-option label="采购羊栋舍" value="采购羊栋舍" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="column" label="栏位" width="100">
          <template #default="{ row }">
            <el-input v-model="row.column" placeholder="请输入栏位" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="birtdate" label="出生日期" width="150">
          <template #default="{ row }">
            <el-date-picker 
              v-model="row.birtdate" 
              type="datetime" 
              placeholder="选择日期时间"
              format="YYYY-MM-DD HH:mm:ss" 
              value-format="YYYY-MM-DDTHH:mm:ss"
              style="width: 100%" 
            />
          </template>
        </el-table-column>
        <el-table-column prop="birthweight" label="出生重(kg)" width="120">
          <template #default="{ row }">
            <el-input v-model="row.birthweight" placeholder="请输入出生重" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="weaning" label="断奶重(kg)" width="120">
          <template #default="{ row }">
            <el-input v-model="row.weaning" placeholder="请输入断奶重" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="parents" label="父号/母号" width="150">
          <template #default="{ row }">
            <el-input v-model="row.parents" placeholder="请输入父号/母号" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="monthber" label="月龄" width="100">
          <template #default="{ row }">
            <el-input v-model="row.monthber" placeholder="请输入月龄" clearable />
          </template>
        </el-table-column>
      </el-table>

      <!-- 操作提示 -->
      <div class="hint" v-if="editingData.length === 0">
        <p class="text-info">点击"增行"添加数据</p>
      </div>
    </el-card>

    <!-- 已保存记录卡片 -->
    <el-card shadow="hover" v-if="savedData.length > 0">
      <template #header>
        <div class="card-header">
          <span class="card-title">已保存记录</span>
          <span class="record-count">共 {{ savedData.length }} 条记录</span>
        </div>
      </template>
      <el-table :data="savedData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="salesId" label="ID" width="80" />
        <el-table-column prop="earNumber" label="耳号" width="120" />
        <el-table-column prop="clinch" label="成交价(元)" width="120" />
        <el-table-column prop="pricing" label="定价(元)" width="120" />
        <el-table-column prop="discount" label="折扣比例" width="120" />
        <el-table-column prop="level" label="等级" width="80" />
        <el-table-column prop="variety" label="品种" width="120" />
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column prop="type" label="羊只类型" width="120" />
        <el-table-column prop="reproduction" label="繁殖状态" width="120" />
        <el-table-column prop="building" label="栋舍" width="120" />
        <el-table-column prop="column" label="栏位" width="100" />
        <el-table-column prop="birtdate" label="出生日期" width="150" />
        <el-table-column prop="birthweight" label="出生重(kg)" width="120" />
        <el-table-column prop="weaning" label="断奶重(kg)" width="120" />
        <el-table-column prop="parents" label="父号/母号" width="150" />
        <el-table-column prop="monthber" label="月龄" width="100" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="editRecord(row)" :icon="Edit" size="small" class="mr-2">
              修改
            </el-button>
            <el-button type="danger" link @click="confirmDelete([row])" :icon="Delete" size="small">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Check, Refresh, Delete, Edit,
  Search, InfoFilled, WarningFilled
} from '@element-plus/icons-vue'
import axios from 'axios'

interface SalesRecord {
  salesId: number
  earNumber: string
  clinch: string
  pricing: string
  discount: string
  level: string
  variety: string
  sex: string
  type: string
  reproduction: string
  building: string
  column: string
  birtdate: string
  birthweight: string
  weaning: string
  parents: string
  monthber: string
  monthsday: string
  isDeleted: boolean
}

interface SaleInfo {
  salesDate: string
  customer: string
  salesperson: string
  department: string
  warehouse: string
  shippingaddress: string
  documentnumber: string
  serialnumber: string
}

const saleInfo = reactive<SaleInfo>({
  salesDate: '',
  customer: '',
  salesperson: '',
  department: '',
  warehouse: '',
  shippingaddress: '',
  documentnumber: '',
  serialnumber: ''
})

const editingData = ref<SalesRecord[]>([])
const savedData = ref<SalesRecord[]>([])
const selectedRows = ref<SalesRecord[]>([])
const isLoading = ref(false)
let recordIndex = 1

// 新增记录
const addNewRecord = () => {
  editingData.value = []
  addRow()
  ElMessage.info('已创建新记录，请添加数据')
}

// 添加表格行
const addRow = () => {
  isLoading.value = true
  // 模拟加载延迟
  setTimeout(() => {
    editingData.value.push({
      salesId: 0,
      earNumber: '',
      clinch: '',
      pricing: '',
      discount: '',
      level: '',
      variety: '',
      sex: '',
      type: '',
      reproduction: '',
      building: '',
      column: '',
      birtdate: '',
      birthweight: '',
      weaning: '',
      parents: '',
      monthber: '',
      monthsday: '',
      isDeleted: false
    })
    isLoading.value = false
  }, 200)
}

// 删除表格行
const deleteRow = () => {
  if (editingData.value.length > 0) {
    editingData.value.pop()
    if (editingData.value.length === 0) {
      recordIndex = 1
    }
    ElMessage.success('已删除最后一行')
  } else {
    ElMessage.warning('没有可删除的行')
  }
}

// 保存记录
const saveRecords = async () => {
  try {
    // 验证必填字段
    if (!saleInfo.salesDate) {
      ElMessage.warning('请选择销售日期')
      return
    }
    if (!saleInfo.customer) {
      ElMessage.warning('请输入客户')
      return
    }
    if (!saleInfo.salesperson) {
      ElMessage.warning('请输入销售员')
      return
    }

    // 校验表格数据
    if (!editingData.value || editingData.value.length === 0) {
      ElMessage.warning('请至少添加一条销售明细')
      return
    }

    // 过滤有效数据
    const validRecords = editingData.value.filter(record =>
      record.earNumber || record.variety || record.sex || record.type || record.building
    )

    if (validRecords.length === 0) {
      ElMessage.warning('请至少填写一条完整的销售明细')
      return
    }

    // 格式化日期为ISO格式
    let formattedDate = ''
    if (saleInfo.salesDate) {
      if (typeof saleInfo.salesDate === 'string') {
        if (saleInfo.salesDate.includes('T')) {
          formattedDate = saleInfo.salesDate
        } else {
          formattedDate = new Date(saleInfo.salesDate).toISOString()
        }
      } else {
        formattedDate = new Date(saleInfo.salesDate).toISOString()
      }
    }

    // 构建API请求数据
    const apiPayload = {
      salesDate: formattedDate,
      customer: saleInfo.customer,
      salesperson: saleInfo.salesperson,
      department: saleInfo.department,
      warehouse: saleInfo.warehouse,
      shippingaddress: saleInfo.shippingaddress,
      documentnumber: saleInfo.documentnumber,
      serialnumber: saleInfo.serialnumber,
      salesList: validRecords.map(row => ({
        salesId: row.salesId,
        earNumber: row.earNumber,
        clinch: row.clinch,
        pricing: row.pricing,
        discount: row.discount,
        level: row.level,
        variety: row.variety,
        sex: row.sex,
        type: row.type,
        reproduction: row.reproduction,
        building: row.building,
        column: row.column,
        birtdate: row.birtdate,
        birthweight: row.birthweight,
        weaning: row.weaning,
        parents: row.parents,
        monthber: row.monthber,
        monthsday: row.monthsday,
        isDeleted: false
      }))
    }

    console.log('发送到后端的数据:', JSON.stringify(apiPayload, null, 2))

    // 使用axios发送请求
    console.log('开始发送请求到:', 'http://localhost:5008/api/Management/CreateSale')
    console.log('请求数据:', apiPayload)
    
    const response = await axios.post('http://localhost:5008/api/Management/CreateSale', apiPayload, {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      timeout: 10000
    })
    
    console.log('后端响应状态:', response.status)
    console.log('后端响应数据:', response.data)

    if (response.status === 200) {
      if (response.data && (response.data.success === true || response.data.code === 200 || response.data.message === 'success' || response.data.code === 100)) {
        ElMessage.success(`保存成功，共保存${validRecords.length}条记录`)
        
        // 清空表单数据
        Object.assign(saleInfo, {
          salesDate: '',
          customer: '',
          salesperson: '',
          department: '',
          warehouse: '',
          shippingaddress: '',
          documentnumber: '',
          serialnumber: ''
        })
        
        // 重置表格数据
        editingData.value = []
        recordIndex = 1
      } else {
        console.log('后端返回失败状态:', response.data)
        ElMessage.error(`保存失败: ${response.data?.message || response.data?.msg || '后端返回失败状态'}`)
      }
    } else {
      console.log('HTTP状态码不是200:', response.status)
      ElMessage.error(`保存失败，HTTP状态码: ${response.status}`)
    }
  } catch (error: any) {
    console.log('=== 请求异常详情 ===')
    console.error('保存失败:', error)
    
    if (error.response) {
      console.log('错误响应状态:', error.response.status)
      console.log('错误响应数据:', error.response.data)
      
      if (error.response.status === 400) {
        console.log('400错误详情:', error.response.data)
        if (error.response.data?.errors) {
          const validationErrors = error.response.data.errors
          let errorMessage = '保存失败: 数据验证错误\n'
          for (const field in validationErrors) {
            errorMessage += `${field}: ${validationErrors[field].join(', ')}\n`
          }
          ElMessage.error(errorMessage)
        } else {
          ElMessage.error(`保存失败: 请求参数错误(400) - ${error.response.data?.title || error.response.data?.message || '请检查数据格式'}`)
        }
      } else if (error.response.status === 404) {
        ElMessage.error('保存失败: API接口不存在(404)，请检查后端路由配置')
      } else if (error.response.status === 401) {
        ElMessage.error('保存失败: 未授权(401)，请检查认证信息')
      } else if (error.response.status === 500) {
        ElMessage.error('保存失败: 服务器内部错误(500)')
      } else {
        ElMessage.error(`保存失败: ${error.response.status} - ${error.response.data?.message || error.response.data?.msg || '服务器错误'}`)
      }
    } else if (error.request) {
      console.log('网络请求失败:', error.request)
      ElMessage.error('保存失败: 网络连接异常，请检查后端服务是否启动在端口5008')
    } else if (error.code === 'ECONNABORTED') {
      console.log('请求超时:', error.message)
      ElMessage.error('保存失败: 请求超时，请检查网络连接')
    } else {
      console.log('其他错误:', error.message)
      ElMessage.error(`保存失败: ${error.message}`)
    }
  }
}

// 编辑记录
const editRecord = (record: SalesRecord) => {
  editingData.value = [JSON.parse(JSON.stringify(record))]
  ElMessage.info('已加载记录到编辑区，请修改后保存')
}

// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要撤销当前编辑内容吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    editingData.value = []
    recordIndex = 1
    ElMessage.success('已撤销')
  }).catch(() => {
    // 取消操作
  })
}

// 处理表格选择
const handleSelectionChange = (rows: SalesRecord[]) => {
  selectedRows.value = rows
}

// 删除选中记录
const deleteSelected = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  confirmDelete(selectedRows.value)
}

// 确认删除
const confirmDelete = (records: SalesRecord[]) => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${records.length} 条记录吗？`,
    '确认删除',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    isLoading.value = true
    // 模拟删除延迟
    setTimeout(() => {
      const recordIds = records.map(r => r.salesId)
      savedData.value = savedData.value.filter(item => !recordIds.includes(item.salesId))
      selectedRows.value = []
      isLoading.value = false
      ElMessage.success(`已成功删除 ${records.length} 条记录`)
    }, 300)
  }).catch(() => {
    // 取消删除
  })
}
</script>

<style scoped>
.sheep-sale-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #409eff;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

/* 操作按钮区域 */
.action-buttons {
  margin: 20px 0;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.mr-2 {
  margin-right: 8px;
}

/* 卡片样式 */
.el-card {
  transition: all 0.3s ease;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1) !important;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.card-title {
  font-size: 16px;
  color: #303133;
}

.record-count {
  font-size: 14px;
  color: #606266;
}

/* 表格样式 */
.el-table {
  margin-top: 16px;
  border-radius: 4px;
  overflow: hidden;
}

.el-table__header {
  background-color: #f5f7fa;
}

.el-table__header th {
  font-weight: 600;
  background-color: #f5f7fa;
}

.el-table__body tr:hover>td {
  background-color: #f0f9ff !important;
}

/* 表格操作按钮 */
.table-actions {
  display: flex;
  gap: 8px;
}

/* 提示信息 */
.hint {
  margin-top: 16px;
  padding: 12px;
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
  border-radius: 4px;
}

.text-info {
  color: #409eff;
  font-size: 14px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sheep-sale-container {
    padding: 12px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .table-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .el-table {
    font-size: 12px;
  }

  .el-table-column {
    width: auto !important;
    min-width: 60px;
  }
}

/* 过渡动画 */
.el-table,
.el-card {
  animation: fadeInUp 0.5s ease;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 输入框聚焦样式 */
:deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 按钮悬停效果 */
:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

/* 按钮点击效果 */
:deep(.el-button:active) {
  transform: translateY(0);
}
</style>